package com.millstein.realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.PropertyNamingStrategy;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.millstein.realtime.app.base.BaseAppV1;
import com.millstein.realtime.bean.UserLoginBean;
import com.millstein.realtime.common.Constants;
import com.millstein.realtime.util.CommonUtil;
import com.millstein.realtime.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessAllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;
import java.util.Date;

public class Dws_04_UserUserLoginWindow extends BaseAppV1 {
    
    public static void main(String[] args) {
        new Dws_04_UserUserLoginWindow().init(
                8004,
                2,
                "Dws_04_UserUserLoginWindow",
                Constants.TOPIC_DWD_TRAFFIC_PAGE
        );
    }

    /**
     * 具体数据处理的逻辑，由子类编写
     *
     * @param env          执行环境对象
     * @param streamSource 待处理的数据流
     */
    @Override
    protected void handle(StreamExecutionEnvironment env, DataStreamSource<String> streamSource) {
        // 1.过滤出登录记录
        SingleOutputStreamOperator<JSONObject> loginStream = filterAndBuildLoginRecordStream(streamSource);
        // 2.过滤出当天独立登录记录和七日回流的登录记录
        SingleOutputStreamOperator<UserLoginBean> recordStream = filterUvAndBackUv(loginStream);
        // 3.开窗聚合
        SingleOutputStreamOperator<UserLoginBean> resultStream = windowAndAgg(recordStream);resultStream.print();
        // 4.写到doris中
        writeToDoris(resultStream);
    }

    /**
     * 过滤出所有的登录记录。过滤的逻辑是：
     *      手动登录uid != null && lastPageId == login
     *      自动登录uid != null lastPageId == null
     * @param streamSource dwd层page的日志数据
     * @return
     */
    private SingleOutputStreamOperator<JSONObject> filterAndBuildLoginRecordStream(
            DataStreamSource<String> streamSource
    ) {
        return streamSource
                .map(new MapFunction<String, JSONObject>() {
                    @Override
                    public JSONObject map(String value) throws Exception {
                        return JSONObject.parseObject(value);
                    }
                })
                .filter(new FilterFunction<JSONObject>() {
                    @Override
                    public boolean filter(JSONObject value) throws Exception {
                        // 手动登录uid != null && (lastPageId == login)
                        // 自动登录uid != null lastPageId == null
                        String uid = value.getJSONObject("common").getString("uid");
                        String lastPageId = value.getJSONObject("page").getString("last_page_id");
                        return uid != null
                                && ("login".equals(lastPageId) || lastPageId == null);
                    }
                });
    }

    /**
     * 从登录记录中找出如下条件的记录：当天有多少人登录的，在这个基础上再找出这些登录的人中有哪些的前一次登录日期是7天前
     * 通过设置一个lastLoginDate的state即可
     * @param loginStream 登录记录
     * @return
     */
    private SingleOutputStreamOperator<UserLoginBean> filterUvAndBackUv(
            SingleOutputStreamOperator<JSONObject> loginStream
    ) {
        return loginStream
                .keyBy(item -> item.getJSONObject("common").getString("uid"))
                .process(new KeyedProcessFunction<String, JSONObject, UserLoginBean>() {
                    ValueState<String> lastLoginDateState;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        lastLoginDateState = getRuntimeContext().getState(
                                new ValueStateDescriptor<>("lastLoginDateState", String.class)
                        );
                    }

                    @Override
                    public void processElement(
                            JSONObject value,
                            Context ctx,
                            Collector<UserLoginBean> out
                    ) throws Exception {
                        Long ts = value.getLong("ts");
                        String today = CommonUtil.formatDate(ts);
                        String lastLoginDate = lastLoginDateState.value();
                        if (!today.equals(lastLoginDate)) {
                            out.collect(UserLoginBean.builder()
                                    .uuCt(1L)
                                    .backCt(0L)
                                    .ts(ts)
                                    .build());
                            if (lastLoginDate != null) {
                                Date lastLogin = CommonUtil.parseDate(lastLoginDate);
                                Date todayLogin = CommonUtil.parseDate(today);
                                if ((todayLogin.getTime() - lastLogin.getTime()) > 1000 * 60 * 60 * 7) {
                                    out.collect(UserLoginBean.builder()
                                            .uuCt(0L)
                                            .backCt(1L)
                                            .ts(ts)
                                            .build());
                                }
                            }
                            lastLoginDateState.update(today);
                        }
                    }
                });
    }

    /**
     * 开窗聚合
     * @param recordStream 符合要求的登录记录
     * @return
     */
    private SingleOutputStreamOperator<UserLoginBean> windowAndAgg(
            SingleOutputStreamOperator<UserLoginBean> recordStream
    ) {
        return recordStream
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy
                                .<UserLoginBean>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                                .withTimestampAssigner(new SerializableTimestampAssigner<UserLoginBean>() {
                                    @Override
                                    public long extractTimestamp(UserLoginBean element, long recordTimestamp) {
                                        return element.getTs();
                                    }
                                })
                )
                .windowAll(TumblingEventTimeWindows.of(Time.seconds(5)))
                .reduce(
                        new ReduceFunction<UserLoginBean>() {
                            @Override
                            public UserLoginBean reduce(
                                    UserLoginBean value1,
                                    UserLoginBean value2
                            ) throws Exception {
                                value1.setUuCt(value1.getUuCt() + value2.getUuCt());
                                value1.setBackCt(value1.getBackCt() + value2.getBackCt());
                                return value1;
                            }
                        },
                        new ProcessAllWindowFunction<UserLoginBean, UserLoginBean, TimeWindow>() {
                            @Override
                            public void process(
                                    Context context,
                                    Iterable<UserLoginBean> elements,
                                    Collector<UserLoginBean> out
                            ) throws Exception {
                                UserLoginBean bean = elements.iterator().next();
                                String startTime = CommonUtil.formatTime(context.window().getStart());
                                String endTime = CommonUtil.formatTime(context.window().getEnd());
                                String curDate = startTime.substring(0, 10);
                                bean.setStt(startTime);
                                bean.setEdt(endTime);
                                bean.setCurDate(curDate);
                                out.collect(bean);
                            }
                        }
                );
    }

    /**
     * 将结果写到doris中
     * @param resultStream 处理后的数据流
     */
    private void writeToDoris(SingleOutputStreamOperator<UserLoginBean> resultStream) {
        resultStream
                .map(bean -> {
                    SerializeConfig config = new SerializeConfig();
                    config.propertyNamingStrategy = PropertyNamingStrategy.SnakeCase;
                    return JSON.toJSONString(bean, config);
                })
                .addSink(FlinkSinkUtil.getDorisSink("gmall.dws_user_user_login_window"));
    }
}
